package com.tsing.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tsing.common.result.Result;
import com.tsing.service.CollectService;
import com.tsing.service.impl.CollectServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @auth 卢孝宇
 * @date 2023/12/14 9:22
 */
public class CollectController {

    private CollectService collectService = new CollectServiceImpl();
    //新增用户收藏
    public Result add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;utf-8");

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonRequest = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonRequest.append(line);
        }

        JSONObject jsonObject = JSON.parseObject(jsonRequest.toString());

        Integer userId = jsonObject.getInteger("userId");
        userId = (userId != null && userId > 0) ? userId : null;

        Integer postId =  jsonObject.getInteger("postId");
        postId = (postId != null && postId > 0) ? postId : null;

        Integer list = collectService.add(userId,postId);

        return Result.success(list);
    }

    //删除用户收藏
    public Result delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;utf-8");

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonRequest = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonRequest.append(line);
        }

        JSONObject jsonObject = JSON.parseObject(jsonRequest.toString());

        Integer userId =  jsonObject.getInteger("userId");
        userId = (userId != null && userId > 0) ? userId : null;

        Integer postId =  jsonObject.getInteger("postId");
        postId = (postId != null && postId > 0) ? postId : null;

        Integer list = collectService.delete(userId,postId);

        return Result.success(list);
    }
}
